﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Serialization;
using System.IO;

#endregion


namespace ESF.General.Text
{
	[Serializable]
	[DataContract]
	public class FileRegisterValidator
	{
		#region Members
		
		[DataMember]
		public int RegisterType { set; get; }

		[DataMember]
		public string Name { set; get; }

		[DataMember]
		public int? Length { set; get; }

		[DataMember]
		public bool IsRequired { set; get; }

		[DataMember]
		public int Position { set; get; }

		[DataMember]
		public string RegularExpression { set; get; }

		[DataMember]
		public bool IsSequence { set; get; }

		[DataMember]
		public int? SumRegisterType { set; get; }

		[DataMember]
		public int? SumRegisterIndex { set; get; }

		[DataMember]
		public string [] AllowedValues { set; get; }

		[DataMember]
		public bool IsRegisterCount { set; get; }

		[DataMember]
		public bool IsIdentificationTypeCode { set; get; }

		[DataMember]
		public bool IsIdentificationNumber { set; get; }

		#endregion


		#region Calculados

		public double calCurrentValueSum;

		public double calSumValue;

		public int calSecuence;

		public int calRegisterCount;

		#endregion


		#region Constructor

		public FileRegisterValidator ()
		{
			calCurrentValueSum = 0;

			calSumValue = 0;

			calSecuence = 0;
		}

		#endregion


		#region Method

		internal void Validate (string pFileName, int pRegType, int pPosition, int pLineNumber, string pValue)
		{
			if (TextHelper.IsEmpty (pValue))
			{
				if (IsRequired)
				{
					throw new GenericValidationException ("Esta vacio y es requerido", pFileName, pLineNumber, pPosition + 1, pRegType.ToString (), Name, pValue);
				}
				else
				{
					return;
				}
			}

			if (!Regex.IsMatch (pValue, "^" + RegularExpression + "$"))
			{
				throw new GenericValidationException ("Tiene un formato invalido", pFileName, pLineNumber, pPosition + 1, pRegType.ToString (), Name, pValue);
			}

			if (!DataHelper.IsEmpty (AllowedValues) && !AllowedValues.Contains (pValue))
			{
				throw new GenericValidationException (string.Format ("Su valor no corresponde a uno de estos: {0}", TextHelper.Concatenate (", ", AllowedValues)), pFileName, pLineNumber, pPosition + 1, pRegType.ToString (), Name, pValue);
			}

			if (Length != null && Length.Value > 0 && pValue.Length > Length.Value)
			{
				throw new GenericValidationException(string.Format("La longitud {0} es superior a la máxima permitida {1}", pValue.Length, Length), pFileName, pLineNumber, pPosition + 1, pRegType.ToString(), Name, pValue);
			}
		}

		#endregion


		#region ToString 

		public override string ToString()
		{
			return string.Format ("{0}-{1}: {2}", RegisterType, Name, RegularExpression);
		}

		#endregion
	}
}
